package com.example.zero.Activity;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zero.Bean.JellyInterpolator;
import com.example.zero.R;
import com.example.zero.Utils.ApplicationUtil;
import com.example.zero.Utils.HttpUtils;
import com.example.zero.Utils.SharedPreUtil;
import com.example.zero.Utils.TimeCount;
import com.example.zero.Utils.ToastUtil;
import com.example.zero.Utils.UrlConstants;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ZLoginActivity extends Activity implements OnClickListener {

	private TextView mBtnLogin;

	private View progress;

	private View mInputLayout;

	private float mWidth, mHeight;

	private LinearLayout mName, mPsw;

	private EditText username, userpassword;

    private TitleBar mTitleBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_zlogin);
		initView();
		initTitleBar();
        ApplicationUtil.getInstance().addActivity(this);
	}

	private void initView() {
		mBtnLogin = (TextView) findViewById(R.id.main_btn_login);
		progress = findViewById(R.id.layout_progress);
		mInputLayout = findViewById(R.id.input_layout);
		mName = (LinearLayout) findViewById(R.id.input_layout_name);
		mPsw = (LinearLayout) findViewById(R.id.input_layout_psw);
		username = (EditText) findViewById(R.id.login_username);
		userpassword = (EditText) findViewById(R.id.login_password);
		mBtnLogin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		mWidth = mBtnLogin.getMeasuredWidth();
		mHeight = mBtnLogin.getMeasuredHeight();

		mName.setVisibility(View.INVISIBLE);
		mPsw.setVisibility(View.INVISIBLE);
		Log.d("mBtnLogin","mBtnLogin is clicked");
		inputAnimator(mInputLayout, mWidth, mHeight);

	}

	private void inputAnimator(final View view, float w, float h) {

		Log.d("inputAnimator","enter inputAnimator");
		final String username_str = username.getText().toString();
		final String userpassword_str = userpassword.getText().toString();
		Log.d("user","username: "+username_str+" pwd: "+userpassword_str);
		ValueAnimator animator = ValueAnimator.ofFloat(0, w);
		animator.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				float value = (Float) animation.getAnimatedValue();
				MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
				params.leftMargin = (int) value;
				params.rightMargin = (int) value;
				view.setLayoutParams(params);
			}
		});
		AnimatorSet set = new AnimatorSet();
		ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout, "scaleX", 1f, 0.5f);
		set.setDuration(600);
		set.setInterpolator(new AccelerateDecelerateInterpolator());
		set.playTogether(animator, animator2);
		set.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator animation) {
				Log.d("inputAnimator","enter onAnimationStart");
			}

			@Override
			public void onAnimationRepeat(Animator animation) {
				Log.d("inputAnimator","enter onAnimationRepeat");

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				Log.d("inputAnimator","enter onAnimationEnd");
				progress.setVisibility(View.VISIBLE);
				progressAnimator(progress);
				mInputLayout.setVisibility(View.INVISIBLE);

				new Handler().postDelayed(new Runnable() {
					public void run() {
						invokeLoginApi(username_str,userpassword_str);
					}
				}, 2000);
			}

			@Override
			public void onAnimationCancel(Animator animation) {
				Log.d("inputAnimator","enter onAnimationCancel");

			}
		});
        set.start();
	}

	private void progressAnimator(final View view) {
		PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX", 0.5f, 1f);
		PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY", 0.5f, 1f);
		ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(view, animator, animator2);
		animator3.setDuration(1000);
		animator3.setInterpolator(new JellyInterpolator());
		animator3.start();

	}

	private void recovery(String callbackMsg) {
		progress.setVisibility(View.GONE);
		mInputLayout.setVisibility(View.VISIBLE);
		mName.setVisibility(View.VISIBLE);
		mPsw.setVisibility(View.VISIBLE);

		MarginLayoutParams params = (MarginLayoutParams) mInputLayout.getLayoutParams();
		params.leftMargin = 0;
		params.rightMargin = 0;
		mInputLayout.setLayoutParams(params);
		
		
		ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout, "scaleX", 0.5f,1f );
		animator2.setDuration(500);
		animator2.setInterpolator(new AccelerateDecelerateInterpolator());
		animator2.start();
        ToastUtil.makeText(ZLoginActivity.this,callbackMsg);
	}
	
	private void invokeLoginApi(final String username_str,String userpassword_str){
		if (!HttpUtils.isNetworkAvalible(getBaseContext())) {
			Toast.makeText(getBaseContext(),"Can not connect to server， please check network configuration!", Toast.LENGTH_SHORT).show();
		} else {
			Map<String,String> map = new HashMap<String,String>();
			map.put("loginId",username_str);
			map.put("password",userpassword_str);
			Callback callback = new Callback() {
				String callbackMsg = "";
				@Override
				public void onFailure(Call call, IOException e) {
					Log.e("setOnClickListener",e.getMessage());
					ToastUtil.makeText(ZLoginActivity.this,"Login failed, please try again");
				}

				@Override
				public void onResponse(Call call, Response response) throws IOException {
					Log.e("response","response: "+response);
					Message message = new Message();
					try {
						if (response.isSuccessful()){
							Log.e("setOnClickListener","response isSuccessful");
							JSONObject jsonObject = new JSONObject(response.body().string());
							String resultCode = jsonObject.getString("resultCode");
							Log.d("resultCode",resultCode);
							if ("00200000".equals(resultCode)){
								message.what = 1;
                                String subsTypes = null;
                                if (jsonObject.getJSONObject("resultInfo")!=null&&jsonObject.getJSONObject("resultInfo").get("subsTypes")!=null){
                                    subsTypes = jsonObject.getJSONObject("resultInfo").get("subsTypes").toString();
                                }
								SharedPreUtil.setParam(ZLoginActivity.this, SharedPreUtil.IS_LOGIN, true);
								SharedPreUtil.setParam(ZLoginActivity.this, SharedPreUtil.LOGIN_DATA, username_str);
								if (!TextUtils.isEmpty(subsTypes)){
									SharedPreUtil.setParam(ZLoginActivity.this, SharedPreUtil.USER_DATA_SUB, subsTypes);
								}
								Intent intent = new Intent(ZLoginActivity.this, MainActivity.class);
								TimeCount.getInstance().setTime(System.currentTimeMillis());
								startActivity(intent);
								finish();
							}else if("00400002".equals(resultCode)){
							    Log.d("resultCode",resultCode);
								message.what = -1;
								callbackMsg = "Incorrect username or password";
							}else {
                                Log.d("else case","starting......");
								message.what = -1;
								callbackMsg = "Login failed, please try again";
							}
						}else {
							Log.d("else case 2","starting......");
							message.what = -1;
							callbackMsg = "Login failure,please check the network";
						}
					}catch (Exception e){
						message.what = -1;
						e.printStackTrace();
						callbackMsg = "Login failed, please try again";
					}finally {
						Bundle b = new Bundle();
						b.putString("callbackMsg", callbackMsg);
						message.setData(b);
						// 发送消息到消息队列中
						handler.sendMessage(message);
					}
				}
			};
			HttpUtils.requestPostHttp(UrlConstants.USER_LOGIN,map,callback);
		}
	}
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case -1:
					Bundle b = msg.getData();
					String callbackMsg = b.getString("callbackMsg");
					recovery(callbackMsg);
					break;
			}
		};
	};
    private void initTitleBar(){
        mTitleBar = (TitleBar) findViewById(R.id.login_title_bar);
        mTitleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
				Intent intent = new Intent(getBaseContext(), RegisterActivity.class);
				startActivity(intent);
            }
        });
    }
}
